package com.pys.beans;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.apache.commons.lang.StringUtils;

import com.pys.common.beans.BaseBean;
import com.pys.pojo.PysTalepTip;
import com.pys.service.TalepTipService;
import com.pys.utils.FacesUtils;

@ManagedBean
@ViewScoped
public class TalepTipBean extends BaseBean implements Serializable {
	private String ad;
	private boolean durum = true;
	private List<PysTalepTip> list;
	private PysTalepTip selectedTalepTip;

	public TalepTipBean() {
		refreshList();
	}

	/*
	 * ACTIONS
	 */
	public void refreshList() {
		TalepTipService talepTipService = new TalepTipService();
		list = talepTipService.getAllList(false);
	}

	public void saveAction() {
		if (StringUtils.isBlank(ad)) {
			FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR,
					"VALIDATION_TALEP_TIP_AD");
			return;
		}

		TalepTipService talepTipService = new TalepTipService();
		if (selectedTalepTip == null) {
			PysTalepTip pysTalepTip = new PysTalepTip();
			pysTalepTip.setAd(ad);
			pysTalepTip.setDurum(durum);
			pysTalepTip.setOlusturmaTarih(new Date());
			pysTalepTip.setPysKullanici(FacesUtils.getUserSession()
					.getCurrentUser());
			talepTipService.save(pysTalepTip);
		} else {
			selectedTalepTip.setAd(ad);
			selectedTalepTip.setDurum(durum);
			selectedTalepTip.setGuncellemeTarih(new Date());
			selectedTalepTip.setPysKullanici(FacesUtils.getUserSession()
					.getCurrentUser());
			talepTipService.update(selectedTalepTip);
		}
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void deleteAction() {
		TalepTipService talepTipService = new TalepTipService();
		selectedTalepTip.setDurum(true);
		talepTipService.update(selectedTalepTip);
		refreshList();
		clear();
		FacesUtils.successMessage();
	}

	public void updateAction() {
		ad = selectedTalepTip.getAd();
		durum = selectedTalepTip.isDurum();
	}

	public void clear() {
		selectedTalepTip = null;
		ad = null;
		durum = true;
	}

	/*
	 * GETTER-SETTER
	 */

	public String getAd() {
		return ad;
	}

	public void setAd(String ad) {
		this.ad = ad;
	}

	public List<PysTalepTip> getList() {
		return list;
	}

	public void setList(List<PysTalepTip> list) {
		this.list = list;
	}

	public PysTalepTip getSelectedTalepTip() {
		return selectedTalepTip;
	}

	public void setSelectedTalepTip(PysTalepTip selectedTalepTip) {
		this.selectedTalepTip = selectedTalepTip;
	}

	public boolean isDurum() {
		return durum;
	}

	public void setDurum(boolean durum) {
		this.durum = durum;
	}

}
